const symbolPrefix = Symbol('prefix')
const _ = require('lodash')
const glob = require('glob')
const { resolve } = require('path')
const Router = require('koa-router')

//todo 处理controller的前缀url
const normalizePath = path => path.startsWith('/') ? path : `/${path}`
export const controller = path => target => target.prototype[symbolPrefix] = normalizePath(path)

//todo 处理方法及方法url
const routerMap = new Map()

const router = conf => (target, key, descriptor) => {
    conf.path = normalizePath(conf.path)

    routerMap.set({
        ...conf,
        target
    }, target[key])
}

export const get = path => router({
    path,
    method: 'get'
})

export const post = path => router({
    path,
    method: 'post'
})

export const put = path => router({
    path,
    method: 'put'
})

export const del = path => router({
    path,
    method: 'del'
})

export const use = path => router({
    path,
    method: 'use'
})

export const all = path => router({
    path,
    method: 'all'
})
//todo 暴露router.foo(fullPath, func)类
const isArray = c => _.isArray(c) ? c : [c]

export default class Route {
    constructor(app, routeDicPath){
        this.app = app
        this.routeDicPath = routeDicPath
        this.router = new Router()
    }

    init(){
        //引入文件
        glob.sync(resolve(this.routeDicPath, '**/*.js')).forEach(require)

        //制造router.xx()
        for (let [conf, controllerMethod] of routerMap) {
            let controllerMethods = isArray(controllerMethod)
            let prefix = conf.target[symbolPrefix]
            let routerPath = conf.path
            let fullPath = prefix +routerPath
            let method = conf.method
            this.router[method](fullPath, ...controllerMethods) //fixme 恐怕完全自己来，这个扩展符写不出来
        }

        this.app.use(this.router.routes())
        this.app.use(this.router.allowedMethods())
    }
}
